package PenguinsFarm.Penguins.Stage
{
	import PenguinsFarm.Penguins.PenguinsRenderer;
	import PenguinsFarm.PenguinsFarmView;
	
	import flash.display.MovieClip;
	import flash.geom.Point;
	import flash.geom.Vector3D;

	public class MovingStage implements IPenguinsStage
	{
		private var target:PenguinsRenderer;
		private var timeFactor:Number		=	0;
		private var velocityFactor:Number	=	0;
		
		private var fromVec:Vector3D;
		private var toVec:Vector3D;		
		private var difVec:Vector3D;	
		
		private var hitWaterInterval:Number	=	0.0;
		
		public function MovingStage( target:PenguinsRenderer )
		{
			this.target	=	target;
			
			var view:PenguinsFarmView =	Global.CoreSNSFramework.getArchView( ShareMacros.MODULE_PENGUINS_FARM ) as PenguinsFarmView;
			var to:Point	=	view.getCageBackground().getRandomGroundPoint();
			
			fromVec			=	new Vector3D( target.x, target.y );
			toVec			=	new Vector3D( to.x, to.y );
			difVec			=	toVec.subtract( fromVec );
			velocityFactor	=	45.0 / difVec.length;
			
			var mc:MovieClip	=	target.getAssetPtr();
			
			var angle:Number	=	getVecDegree( difVec );
			if( angle <= 45 )
			mc.gotoAndPlay( "move4" );
			
			else if( angle <= 135 )
			mc.gotoAndPlay( "move3" );
			
			else if( angle <= 225 )
			mc.gotoAndPlay( "move2" );
			
			else if( angle <= 315 )
			mc.gotoAndPlay( "move1" );
			
			else
			mc.gotoAndPlay( "move4" );			
		}
		
		public function onFrameUpdate( deltaTime:Number ):void
		{
			timeFactor	+=	deltaTime * velocityFactor;
			
			var scaleVec:Vector3D	=	difVec.clone();
			scaleVec.scaleBy( timeFactor );
			
			var curVec:Vector3D	=	fromVec.add( scaleVec );
			target.x	=	curVec.x;
			target.y	=	curVec.y;
			
			//=====
			hitWaterInterval	-=	deltaTime;
			if( hitWaterInterval <= 0 )
			{
				hitWaterInterval	=	0.5;
				
				// Is water zone
				var view:PenguinsFarmView =	Global.CoreSNSFramework.getArchView( ShareMacros.MODULE_PENGUINS_FARM ) as PenguinsFarmView;
				var isInWater:Boolean	=	view.getCageBackground().isHitWater( target );
				target.applySwimmingStage( isInWater );
			}
		}
		
		public function dispose():void
		{
			fromVec	=	null;
			toVec	=	null;		
			difVec	=	null;
		}		
		
		public function isCompleteStage():Boolean
		{
			return timeFactor >= 1.0;	
		}		
		
		private function getVecDegree( vec:Vector3D ):Number
		{
			var norVec:Vector3D	=	vec.clone();
			norVec.normalize();
			
			var result:Number	=	Math.acos( norVec.x ) * 180.0 / Math.PI;
			if( norVec.y <= 0 )
				return result;
			
			return 360.0 - result;
		}
	}
}